﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxClasses;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxGridView.Export;

namespace YXQ.Common.Control
{
    public class RenderGridView
    {
        public static string tb = string.Empty;

        public static void BuildGridView(ASPxGridView gv, string tbName)
        {
            tb = tbName;
            var table = RenderReportTableColumn.GetConfigTables(tbName, Configs.TableConfig).FirstOrDefault();

            if (table != null)
            {
                var columns = table.columns;
                int i = 0;
                foreach (var reportTableColumn in columns)
                {
                    //if (reportTableColumn.IsData)
                    //{
                    i++;

                    var gridcolumn = new GridViewDataTextColumn();
                    gridcolumn.Caption = reportTableColumn.sourceColumnName;
                    gridcolumn.FieldName = reportTableColumn.columnName;
                    gridcolumn.EditFormSettings.VisibleIndex = i;
                    gridcolumn.Visible = reportTableColumn.IsVisible;

                    gv.Columns.Add(gridcolumn);

                    if (reportTableColumn.IsGoupBy)
                    {
                        gv.GroupBy(gv.Columns[reportTableColumn.columnName]);

                    }
                    if (reportTableColumn.IsKey)
                    {

                        gv.KeyFieldName = reportTableColumn.columnName;

                    }
                    //}
                }
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="table"></param>
        /// <param name="grid"></param>
        /// <param name="Permission"></param>
        public static GridViewDataHyperLinkColumn EditColumn(string table, string keyFiledName)
        {

            var editcolum = new GridViewDataHyperLinkColumn();
            editcolum.VisibleIndex = 1;
            editcolum.Width = Unit.Point(50);
            editcolum.Caption = "操作";
            if (table.ToLower().IndexOf("view") > 0)
            {
                table = table.Replace("_View", "");
            }
            editcolum.PropertiesHyperLinkEdit.NavigateUrlFormatString = table + "_Detail.aspx?ID={0}";
            editcolum.PropertiesHyperLinkEdit.Text = "编辑";
            editcolum.FieldName = keyFiledName;
            editcolum.Settings.AllowHeaderFilter = DefaultBoolean.False;
            editcolum.Settings.AllowSort = DefaultBoolean.False;
            editcolum.Settings.AllowAutoFilter = DefaultBoolean.False;
            return editcolum;
        }

        public static string GetWhereFiled(string strFlowWhere)
        {
            string strWhereOrder = string.Empty;


            if (string.IsNullOrEmpty(RenderGridView.sSortDirection))
            {
                RenderGridView.sSortDirection = "asc";
            }
            if (!string.IsNullOrEmpty(RenderGridView.WhereFilds))
            {
                strWhereOrder += RenderGridView.WhereFilds;
            }
            if (!string.IsNullOrEmpty(strFlowWhere))
            {
                strWhereOrder += strFlowWhere;
            }

            if (!string.IsNullOrEmpty(RenderGridView.SortFieldName))
            {
                strWhereOrder += " order by ";
                if (!string.IsNullOrEmpty(RenderGridView.SortFieldName))
                {
                    strWhereOrder += RenderGridView.SortFieldName + " " + RenderGridView.sSortDirection;
                }

            }
            if (!string.IsNullOrEmpty(RenderGridView.GroupFilds))
            {
                strWhereOrder += " Group By " + RenderGridView.GroupFilds;
            }
            return strWhereOrder;
        }


        /// <summary>
        /// 条件过滤
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="e"></param>
        public static void ColumnAutoFilter(ASPxGridView grid, ASPxGridViewAutoFilterEventArgs e)
        {
            grid.FilterExpression = "";
            if (!ReferenceEquals(e.Criteria, null))
            {
                if (RenderGridView.WhereFilds != " and " + e.Criteria.LegacyToString().Replace(e.Value + "%", "%" + e.Value + "%"))
                {
                    RenderGridView.WhereFilds += " and " + e.Criteria.LegacyToString().Replace(e.Value + "%", "%" + e.Value + "%");
                }
            }
            else
            {
                RenderGridView.WhereFilds = "";
            }
        }

        /// <summary>
        /// 分组排序
        /// </summary>
        /// <param name="e"></param>
        public static void ColumnSortingGrouping(ASPxGridViewBeforeColumnGroupingSortingEventArgs e)
        {


            switch (e.Column.SortOrder)
            {
                case DevExpress.Data.ColumnSortOrder.Ascending: RenderGridView.sSortDirection = "asc";
                    break;
                case DevExpress.Data.ColumnSortOrder.Descending: RenderGridView.sSortDirection = "desc";
                    break;
            }

            RenderGridView.SortFieldName = e.Column.FieldName;
        }



        /// <summary>
        /// 数字枚举转换为汉字
        /// </summary>
        /// <param name="e"></param>
        public static void ConvertEnum(ASPxGridViewColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName.ToLower().IndexOf("is") >= 0)
            {
               // e.DisplayText = Enum.Parse(typeof(IsStart), e.Value.ToString()).ToString();
                return;
            }

            if (!string.IsNullOrEmpty(e.Value.ToString()))
            {
                switch (e.Column.FieldName)
                {
                    default: break;
                }
            }
        }


        public static List<string> GetSelectRows(ASPxGridView grid)
        {
            List<object> values = grid.GetSelectedFieldValues(new string[] { grid.KeyFieldName });
            List<string> str = new List<string>(values.Count);//初始化
            for (int i = 0; i < values.Count; i++)
                str.Add(values[i].ToString());
            return str;
        }




        /// <summary>
        /// 表头功能实现
        /// </summary>
        /// <param name="grid">表格</param>
        /// <param name="button">表头按钮</param>
        /// <param name="oname">按钮原来的名字</param>
        /// <param name="nname">按钮过后的名字</param>
        /// <param name="ftype">哪种功能</param>
        /// <returns></returns>
        public static string GridFilter(ASPxGridView grid, string ftype)
        {
            string WhereFilds = string.Empty;
            switch (ftype)
            {

                case "filter":

                    if (!string.IsNullOrEmpty(grid.FilterExpression))
                    {
                        WhereFilds = " and " + grid.FilterExpression.Replace("like '", "like '%");
                    }


                    break;
                case "group":
                    if (grid.Settings.ShowGroupPanel == true)
                    {

                        grid.Settings.ShowGroupPanel = false;
                        grid.ClearSort();
                    }
                    else
                    {

                        grid.Settings.ShowGroupPanel = true;
                    }
                    break;
            }
            return WhereFilds;

        }

        /// <summary>
        /// 表头功能实现
        /// </summary>
        /// <param name="grid">表格</param>
        /// <param name="button">表头按钮</param>
        /// <param name="oname">按钮原来的名字</param>
        /// <param name="nname">按钮过后的名字</param>
        /// <param name="ftype">哪种功能</param>
        /// <returns></returns>
        public static string GridFilter(ASPxGridView grid, ASPxButton button, string oname, string nname, string ftype)
        {
            string WhereFilds = string.Empty;
            switch (ftype)
            {

                case "filter":
                    if (grid.Settings.ShowFilterRow == true)
                    {
                        button.Text = oname;
                        grid.FilterEnabled = false;

                        grid.Settings.ShowFilterRow = false;

                    }
                    else
                    {
                        button.Text = nname;
                        grid.FilterEnabled = false;
                        if (!string.IsNullOrEmpty(grid.FilterExpression))
                        {
                            WhereFilds = " and " + grid.FilterExpression.Replace("like '", "like '%");
                        }
                        grid.Settings.ShowFilterRow = true;
                    }
                    break;
                case "group":
                    if (grid.Settings.ShowGroupPanel == true)
                    {
                        button.Text = oname;
                        grid.Settings.ShowGroupPanel = false;
                        grid.ClearSort();
                    }
                    else
                    {
                        button.Text = nname;
                        grid.Settings.ShowGroupPanel = true;
                    }
                    break;
            }
            return WhereFilds;

        }

        public static string SortFieldName
        {
            get
            {
                if (HttpContext.Current.Session[tb + "SortFieldName"] == null)
                    HttpContext.Current.Session[tb + "SortFieldName"] = "";
                return HttpContext.Current.Session[tb + "SortFieldName"].ToString();
            }
            set
            {
                HttpContext.Current.Session[tb + "SortFieldName"] = value;
            }
        }

        public static string sSortDirection
        {
            get
            {
                if (HttpContext.Current.Session[tb + "SortDirection"] == null)
                    HttpContext.Current.Session[tb + "SortDirection"] = "asc";
                return HttpContext.Current.Session[tb + "SortDirection"].ToString();
            }
            set
            {
                HttpContext.Current.Session[tb + "SortDirection"] = value;
            }
        }

        /// <summary>
        /// 多字段查询条件
        /// </summary>
        public static string WhereFilds
        {
            get
            {
                if (HttpContext.Current.Session[tb + "WhereFilds"] == null)
                    HttpContext.Current.Session[tb + "WhereFilds"] = "";
                return HttpContext.Current.Session[tb + "WhereFilds"].ToString();
            }
            set
            {
                HttpContext.Current.Session[tb + "WhereFilds"] = value;
            }
        }

        /// <summary>
        /// 分组字段
        /// </summary>
        public static string GroupFilds
        {
            get
            {
                if (HttpContext.Current.Session[tb + "GroupFilds"] == null)
                    HttpContext.Current.Session[tb + "GroupFilds"] = "";
                return HttpContext.Current.Session[tb + "GroupFilds"].ToString();
            }
            set
            {
                HttpContext.Current.Session[tb + "GroupFilds"] = value;
            }
        }


        public static RenderReportTableColumn.ReportTable BuildASPXNewGridView(ASPxGridView gv, string tbName)
        {
            tb = tbName;
            var table = RenderReportTableColumn.GetConfigTables(tbName, Configs.TableConfig).FirstOrDefault();

            if (table != null)
            {
                var columns = table.columns;
                int i = 0;
                var chkBoxColumn = new GridViewCommandColumn();
                chkBoxColumn.ShowSelectCheckbox = true;
                chkBoxColumn.VisibleIndex = 0;
                chkBoxColumn.Caption = "选择";
                chkBoxColumn.Width = Unit.Point(50);

                if (table.IsMutiSelect)
                {
                    gv.Columns.Insert(0, chkBoxColumn);
                    i = 1;
                }
                foreach (var reportTableColumn in columns)
                {
                    i++;
                    if (reportTableColumn.IsLink)
                    {
                        var linkColumn = new GridViewDataHyperLinkColumn();
                        linkColumn.Caption = reportTableColumn.sourceColumnName;
                        linkColumn.PropertiesHyperLinkEdit.NavigateUrlFormatString = reportTableColumn.Url + "?ID={0}";
                        linkColumn.PropertiesHyperLinkEdit.Text = reportTableColumn.sourceColumnName;
                        linkColumn.Settings.AllowHeaderFilter = DevExpress.Web.ASPxClasses.DefaultBoolean.False;
                        linkColumn.Settings.AllowSort = DevExpress.Web.ASPxClasses.DefaultBoolean.False;
                        linkColumn.Settings.AllowAutoFilter = DevExpress.Web.ASPxClasses.DefaultBoolean.False;
                        linkColumn.EditFormSettings.VisibleIndex = i;
                        var key = columns.FirstOrDefault(op => op.IsKey);
                        linkColumn.FieldName = key == null ? null : key.columnName;
                        gv.Columns.Add(linkColumn);
                    }
                    if (reportTableColumn.IsLink) continue;
                    var gridcolumn = new GridViewDataTextColumn();
                    gridcolumn.Caption = reportTableColumn.sourceColumnName;
                    gridcolumn.FieldName = reportTableColumn.columnName;
                    gridcolumn.EditFormSettings.VisibleIndex = i;
                    gridcolumn.Visible = reportTableColumn.IsVisible;
                    if (reportTableColumn.IsFixedStyle)
                    {
                        gridcolumn.FixedStyle = GridViewColumnFixedStyle.Left;
                    }
                    gv.Columns.Add(gridcolumn);

                    if (reportTableColumn.IsGoupBy)
                    {
                        gv.GroupBy(gv.Columns[reportTableColumn.columnName]);

                    }
                    if (reportTableColumn.IsKey)
                    {
                        gv.KeyFieldName = reportTableColumn.columnName;

                    }

                }
                gv.Caption = table.tableSourceName;
            }
            return table;




        }

        public static ASPxGridView BuildASPXGridView(ASPxGridView gv, string tbName)
        {
            tb = tbName;
            var table = RenderReportTableColumn.GetConfigTables(tbName, Configs.TableConfig).FirstOrDefault();

            if (table != null)
            {
                var columns = table.columns;
                int i = 0;
                var chkBoxColumn = new GridViewCommandColumn();
                chkBoxColumn.ShowSelectCheckbox = true;
                chkBoxColumn.VisibleIndex = 0;
                chkBoxColumn.Caption = "选择";
                chkBoxColumn.Width = Unit.Point(50);

                if (table.IsMutiSelect)
                {
                    gv.Columns.Insert(0, chkBoxColumn);
                    i = 1;
                }
                foreach (var reportTableColumn in columns)
                {
                    i++;
                    if (reportTableColumn.IsLink)
                    {

                        var linkColumn = new GridViewDataHyperLinkColumn();
                        linkColumn.Caption = reportTableColumn.sourceColumnName;
                        linkColumn.PropertiesHyperLinkEdit.NavigateUrlFormatString = reportTableColumn.Url + "?ID={0}";
                        linkColumn.PropertiesHyperLinkEdit.Text = reportTableColumn.sourceColumnName;
                        linkColumn.Settings.AllowHeaderFilter = DevExpress.Web.ASPxClasses.DefaultBoolean.False;
                        linkColumn.Settings.AllowSort = DevExpress.Web.ASPxClasses.DefaultBoolean.False;
                        linkColumn.Settings.AllowAutoFilter = DevExpress.Web.ASPxClasses.DefaultBoolean.False;
                        linkColumn.EditFormSettings.VisibleIndex = i;
                        var key = columns.FirstOrDefault(op => op.IsKey);
                        linkColumn.FieldName = key == null ? null : key.columnName;
                        gv.Columns.Add(linkColumn);
                    }
                    if (reportTableColumn.IsLink) continue;
                    var gridcolumn = new GridViewDataTextColumn();
                    gridcolumn.Caption = reportTableColumn.sourceColumnName;
                    gridcolumn.FieldName = reportTableColumn.columnName;
                    gridcolumn.EditFormSettings.VisibleIndex = i;
                    gridcolumn.Visible = reportTableColumn.IsVisible;
                    if (reportTableColumn.IsFixedStyle)
                    {
                        gridcolumn.FixedStyle = GridViewColumnFixedStyle.Left;
                    }
                    gv.Columns.Add(gridcolumn);

                    if (reportTableColumn.IsGoupBy)
                    {
                        gv.GroupBy(gv.Columns[reportTableColumn.columnName]);

                    }
                    if (reportTableColumn.IsKey)
                    {
                        gv.KeyFieldName = reportTableColumn.columnName;

                    }

                }
                gv.Caption = table.tableSourceName;
            }
            return gv;




        }

        public static void BuildCommonGridView(ASPxGridView gv, string tbName)
        {
            tb = tbName;
            var table = RenderReportTableColumn.GetConfigTables(tbName, Configs.TableConfig).FirstOrDefault();
            if (table != null)
            {
                var columns = table.columns;
                // var editcolum = new GridViewDataColumn();
                //editcolum.DataItemTemplate=
                //ITemplate templete = editcolum.DataItemTemplate;
                //ASPxGridView

                var editcolum = new GridViewDataHyperLinkColumn();
                //var delcolumn = new GridViewDataHyperLinkColumn();
                editcolum.VisibleIndex = 0;
                editcolum.Width = Unit.Point(50);
                editcolum.Caption = "操作";

                if (tbName.ToLower().IndexOf("view") > 0)
                {
                    tbName = tbName.Replace("_View", "");
                }

                editcolum.PropertiesHyperLinkEdit.NavigateUrlFormatString = tbName + "_Detail.aspx?ID={0}";
                editcolum.PropertiesHyperLinkEdit.Text = "编辑";
                editcolum.Settings.AllowSort = DevExpress.Web.ASPxClasses.DefaultBoolean.False;
                editcolum.Settings.AllowAutoFilter = DevExpress.Web.ASPxClasses.DefaultBoolean.False;
                //  editcolum.FixedStyle = GridViewColumnFixedStyle.Left;
                var chkBoxColumn = new GridViewCommandColumn();
                chkBoxColumn.ShowSelectCheckbox = true;
                chkBoxColumn.VisibleIndex = 0;
                chkBoxColumn.Caption = "选择";
                chkBoxColumn.Width = Unit.Point(50);
                //chkBoxColumn.FixedStyle = GridViewColumnFixedStyle.Left;
                int i = 0;
                if (table.IsMutiSelect)
                {
                    gv.Columns.Insert(0, chkBoxColumn);
                    i = 1;
                }
                if (table.IsEdit)
                {
                    if (table.IsMutiSelect)
                    {
                        gv.Columns.Insert(1, editcolum);
                        i = 2;
                    }
                    else
                    {
                        gv.Columns.Insert(0, editcolum);
                        i = 1;
                    }
                }

                foreach (var reportTableColumn in columns)
                {
                    //if (reportTableColumn.IsData)
                    //{
                    i++;

                    //链接列 谢小兵
                    if (reportTableColumn.IsLink)
                    {
                        var linkColumn = new GridViewDataHyperLinkColumn();
                        linkColumn.Caption = reportTableColumn.sourceColumnName;
                        linkColumn.PropertiesHyperLinkEdit.NavigateUrlFormatString = reportTableColumn.Url + "?ID={0}";
                        //显示字段
                        if (string.IsNullOrEmpty(reportTableColumn.TextField))
                            linkColumn.PropertiesHyperLinkEdit.Text = reportTableColumn.columnName;
                        else
                            linkColumn.PropertiesHyperLinkEdit.TextField = reportTableColumn.TextField;

                        linkColumn.Settings.AllowHeaderFilter = DevExpress.Web.ASPxClasses.DefaultBoolean.False;
                        linkColumn.Settings.AllowSort = DevExpress.Web.ASPxClasses.DefaultBoolean.False;
                        linkColumn.Settings.AllowAutoFilter = DevExpress.Web.ASPxClasses.DefaultBoolean.False;
                        linkColumn.EditFormSettings.VisibleIndex = i;
                        //传过去的值  默认是ID
                        if (!string.IsNullOrEmpty(reportTableColumn.FieldName))
                        {
                            linkColumn.FieldName = reportTableColumn.FieldName;
                        }
                        else
                        {
                            var key = columns.FirstOrDefault(op => op.IsKey);
                            linkColumn.FieldName = key == null ? null : key.columnName;
                        }
                        gv.Columns.Add(linkColumn);
                    }
                    if (reportTableColumn.IsLink) continue;

                    var gridcolumn = new GridViewDataTextColumn();
                    gridcolumn.Caption = reportTableColumn.sourceColumnName;
                    gridcolumn.FieldName = reportTableColumn.columnName;
                    gridcolumn.EditFormSettings.VisibleIndex = i;
                    gridcolumn.Visible = reportTableColumn.IsVisible;
                    if (reportTableColumn.IsFixedStyle)
                    {
                        gridcolumn.FixedStyle = GridViewColumnFixedStyle.Left;
                    }
                    gv.Columns.Add(gridcolumn);

                    if (reportTableColumn.IsGoupBy)
                    {
                        gv.GroupBy(gv.Columns[reportTableColumn.columnName]);

                    }
                    if (reportTableColumn.IsKey)
                    {
                        editcolum.FieldName = reportTableColumn.columnName;
                        //delcolumn.FieldName = reportTableColumn.columnName;
                        gv.KeyFieldName = reportTableColumn.columnName;

                    }
                    //}
                }
            }

            //gv.Columns.Insert(1, delcolumn);
            //he bing dan yuan ge
            // gv.HtmlRowCreated += new ASPxGridViewTableRowEventHandler(CellAdd);
        }

        /// <summary>
        /// 导出CVS
        /// </summary>
        /// <param name="gv"></param>
        /// <param name="filename"></param>
        public static void ExportCvs(ASPxGridViewExporter gv, string filename)
        {
            gv.FileName = filename;
            gv.WriteCsvToResponse();
        }
        /// <summary>
        /// 导出Execle
        /// </summary>
        /// <param name="gv"></param>
        /// <param name="filename"></param>
        public static void ExportExecle(ASPxGridViewExporter gv, string filename)
        {
            gv.FileName = filename;
            gv.WriteXlsToResponse();
        }
        /// <summary>
        /// 导出PDF
        /// </summary>
        /// <param name="gv"></param>
        /// <param name="filename"></param>
        public static void ExportPdf(ASPxGridViewExporter gv, string filename)
        {
            gv.FileName = filename;
            gv.WriteRtfToResponse();
        }
    }
}
